<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="keywords" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入名称查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button plain type="primary"  @click="handleAdd" >新增</el-button>

    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="teamEmpList" >
        <el-table-column prop="team_user_name" label="员工姓名" />
        <el-table-column prop="team_emp_avatar" label="员工头像">
          <template v-slot="scope">
            <el-image style="width: 50px; height: 50px; border-radius: 50%; display: block" v-if="scope.row.team_emp_avatar"
                      :src="scope.row.team_emp_avatar" :preview-src-list="[scope.row.team_emp_avatar]" preview-teleported></el-image>
          </template>
        </el-table-column>

        <el-table-column prop="create_time" label="创建时间" >
          <template v-slot="scope">
            {{dayjs(scope.row.create_time).format('YYYY-MM-DD HH:mm:ss')}}
          </template>
        </el-table-column>

        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="id_card" label="身份证" />
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="sex" label="性别" >
          <template #default="scope">
            <span v-if="scope.row.sex === 0">{{  '男'   }}</span>
            <span v-if="scope.row.sex === 1">{{  '女'   }}</span>
            <span v-if="scope.row.sex === null">{{  '未设置'   }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="team_name" label="团队名称" />
        <el-table-column prop="is_leader" label="团队成员" >
          <template v-slot="scope">
            <span v-if="scope.row.is_leader === 0"><el-tag>{{"团队领导"}}</el-tag></span>
            <span v-if="scope.row.is_leader === 1"><el-tag>{{"团队员工"}}</el-tag></span>
            <span v-if="scope.row.is_leader === null"><el-tag>{{"未设置"}}</el-tag></span>
          </template>
        </el-table-column>



        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" >
      <el-pagination :total=total v-model:current-page="pagination.currentPage" :page-size=pagination.pageSize @current-change="load" />
    </div>


    <el-dialog title="团队员工信息" v-model="formVisible" width="50%" destroy-on-close >
      <el-form  :model="form" label-width="70px" style="padding: 20px ">
        <el-form-item prop="team_user_name" label="员工姓名">
          <el-input v-model="form.value.team_user_name" placeholder="请输入员工名称"></el-input>
        </el-form-item>
        <el-form-item prop="team_emp_avatar" label="员工头像">

          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              list-type="picture"
              :headers=token
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item prop="username" label="用户名">
          <el-input v-model="form.value.username" placeholder="请输入员工用户名"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.value.sex">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number
              v-model="form.value.age"
              :min="0"
              :max="120"
              :step="1"
              placeholder="请输入年龄"
          />
        </el-form-item>


        <el-form-item prop="team_id" label="团队名称">

          <el-select v-model="form.value.team_id" placeholder="选择团队" :disabled="true">
            <el-option
                v-for="team in teamList"
                :key="team.team_id"
                :label="team.team_name"
                :value="team.team_id">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="团队角色" prop="is_leader">
          <el-radio-group v-model="form.value.is_leader">
            <el-radio :value="0">团队领导</el-radio>
            <el-radio :value="1">团队成员</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="id_card" label="身份证号">
          <el-input v-model="form.value.id_card" placeholder="请输入身份证号"></el-input>
        </el-form-item>


      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
        title="内容"
        v-model="viewVisible"
        width="50%"
        :close-on-click-modal="false"
        destroy-on-close
    >
      <div
          class="editor-content-view"
          style="padding: 20px"
          v-html="formContent"
      ></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref,reactive,onMounted,onBeforeUnmount, shallowRef } from "vue";

import {ElMessage, ElMessageBox,} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";
import {takeAccessToken} from "@/net/index.js"
import TextEditor from "@/views/TextEditor.vue";
import router from "@/router/index.js";
import {get, post} from "@/net/index.js";
import dayjs from "dayjs";
import { createEditor, createToolbar } from '@wangeditor/editor';  // 使用正确的导出方式



const baseUrl = import.meta.env.VITE_BASE_URL



const pagination = reactive({
  pageSize: 5,
  currentPage: 1,
  total: 0
})

const keywords = ref("")
let token = null
const form=reactive({})
const formContent=ref()
const formVisible= ref(false);
const viewVisible= ref(false);
const total = ref()
const teamEmpList = ref([])
const teamList = ref({
  team_id:"",
  team_name:""
})

const view = (info) => {
  formContent.value = info;
  viewVisible.value = true;
};

const load = () => {
  console.log(keywords.value)
  const userInfo = JSON.parse(localStorage.getItem('user'))
  const teamId = userInfo.team_leader_id
  get(`/api/teamEmp/getTeamEmpListByTeamId/${pagination.currentPage}?keywords=${keywords.value || ''}&teamId=${teamId}`,(res)=>{
    total.value = res.total
    teamEmpList.value = res.list
    // console.log(teamList.value)
    console.log(res)
  },(err)=>{
    ElMessage.warning("请求失败")
    console.log(err)
  })

}


const getAllTeamList = () => {
  get(`/api/team/getAllTeamList`,(res)=>{

    console.log(res)
    teamList.value = res.map(team => ({
      team_id: team.id,
      team_name: team.team_name
    }));
    // console.log(teamList.value)
  },(err)=>{
    ElMessage.warning("请求失败")
    console.log(err)
  })

}


const handleFileUpload=(res)=>{
  // console.log(form.value.avatar)
  form.value.team_emp_avatar = res.data
  // console.log(form.value.avatar)
}

const reset = () => {
  keywords.value = ''
  load()
}

const handleAdd = () => {
  form.value = {}

  const userInfo = JSON.parse(localStorage.getItem('user'));
  form.value.team_id = userInfo.team_leader_id; // 设置当前团队的 ID

  formVisible.value = true
  console.log(form.value )
}

const handleEdit = (row) => {
  form.value = row
  formVisible.value = true
  console.log(form.value )
}



const update = () => {
  post(`/api/teamEmp/updateTeamEmp`,form.value,(res)=>{
    ElMessage.success("修改成功")
    formVisible.value = false
    load()
    // console.log(form.value)
    // console.log(res)

  },(err)=>{
    ElMessage.warning("修改失败")
    console.log(err)
  })
}

const add = () => {
  post(`/api/teamEmp/addTeamEmp`,form.value,(res)=>{
    ElMessage.success("添加成功")
    formVisible.value = false
    load()
    console.log(res)

  },(err)=>{
    ElMessage.warning("添加失败")
    console.log(err)
  })
}

const save = () => {
  // console.log(form.value.id)
  form.value.id ? update() : add()

}

const del = (id) => {

  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {
    type: 'warning', confirmButtonText: '确认删除',
    cancelButtonText: '取消',
  }).then(res => {
    post(`/api/teamEmp/deleteTeamEmp/${id}`, null, (res) => {
      ElMessage.success("删除成功");
      load();
    }, (err) => {
      ElMessage.success("删除失败");
    })
  }).catch(err => {
    console.error(err)
  })
}


onMounted(() => {
  load(1)
  getAllTeamList()
  token = {'Authorization': `Bearer ${takeAccessToken()}`}
  // console.log(token)
  // const teamEmpStore = useTeamEmpStore()
  // const teamEmp = {
  //   'teamEmpname':"admin"
  // }
  // teamEmpStore.setTeamEmp(teamEmp)
  // console.log(teamEmpStore.teamEmp)
  // window.localStorage.getItem('teamEmp')
  // console.log(teamEmpStore.teamEmp)
  // console.log(JSON.parse(window.localStorage.getItem('teamEmp')))
})

</script>

<style scoped>

</style>